package com.cjjd.c.feature.mine.information;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.ActionBarFragment;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.TravellerInfoBean;
import com.cjjd.c.bean.TravellerListBean;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.StringUtil;
import com.cjjd.c.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/8/18.
 * <p/>
 * 描  述：
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class TravellerInforFragment extends ActionBarFragment {

    @Bind(R.id.et_name_zh)
    EditText etNameZh;
    @Bind(R.id.et_firstName)
    EditText etFirstName;
    @Bind(R.id.et_second_name)
    EditText etSecondName;
    @Bind(R.id.tv_id_type)
    TextView tvIdType;
    @Bind(R.id.et_id_num)
    EditText etIdNum;
    @Bind(R.id.tv_birthday)
    TextView tvBirthday;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.et_country)
    EditText etCountry;
    @Bind(R.id.et_phone_num)
    EditText etPhoneNum;
    @Bind(R.id.toggleButton)
    ToggleButton toggleButton;
    @Bind(R.id.tv_del)
    TextView tvDel;
    @Bind(R.id.zhengjian)
    TextView zhengjian;


    private TravellerListBean travellerListBean;

    @Override
    public Object getTitleString() {
        return "常用旅客详情";
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_traveller_info;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        if (!TextUtils.isEmpty(uuid)) {
            getPassangerDetail();
        }
        initView();
        return rootView;
    }

    @Override
    public void initRightButton(Button rightButton) {
        super.initRightButton(rightButton);
        rightButton.setText("保存");
        rightButton.setVisibility(View.VISIBLE);
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkCanUpdate()) {
                    updateTraveller();
                }
            }
        });
    }


    private void updateTraveller() {
        HashMap<String, Object> h1 = new HashMap<>();

        /*
        token	String	会员调用登录接口后，返回的唯一标识
        sessionId	String	会员调用登录接口后，返回的sessionId
        name	String	旅客姓名
        firstname	String	英文姓
        lastname	String	英文名
        idCardType	String	证件类型
        idCardNum	String	证件号码
        birthday	String	生日
        sex	String	性别 1男0女
        country	String	国籍
        mobile	String	手机号码
        isMyself	int	是否本人默认0否1是
        */

        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("uuid", uuid);
        h1.put("name", nameZh);
        h1.put("firstname", firstName);
        h1.put("lastname", secondName);
        h1.put("idCardType", idCardType);
        h1.put("idCardNum", idNum);
        h1.put("birthday", birthday);
        h1.put("sex", sex);                           // 性别： 1男 0女
        h1.put("country", country);
        h1.put("mobile", phoneNum);
        h1.put("isMyself", isMyself);                 // 是否本人默认，0否 1是
        Call<HttpResult<String>> call = service.addPassanger(JsonUtils.convertParam("updatePassanger", h1));
        call.enqueue(new CallbackImpl<String>() {
            @Override
            public void responseSuccess(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                ToastUtil.showToast("更新成功");
                mContext.onBackPressed();
            }
        });

    }

    private String uuid;

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    private void getPassangerDetail() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("uuid", uuid);

        Call<HttpResult<TravellerInfoBean>> call = service.getPassangerDetail(JsonUtils.convertParam("getPassangerDetail", h1));
        call.enqueue(new CallbackImpl<TravellerInfoBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<TravellerInfoBean>> call, Response<HttpResult<TravellerInfoBean>> response) {
                travellerListBean = response.body().getData().passangerModel;

                changeUI(travellerListBean);

            }
        });
    }

    private void changeUI(TravellerListBean travellerListBean) {
        LogUtil.e("xyd","设置界面");
        etNameZh.setText(travellerListBean.name);
        etFirstName.setText(travellerListBean.firstname);
        etSecondName.setText(travellerListBean.lastname);

        // 1身份证2护照3港澳台胞通行证4军官证5士兵证
        idCardType = travellerListBean.idCardType;
        if ("1".equals(travellerListBean.idCardType)) {
            tvIdType.setText("身份证");
        } else if ("2".equals(travellerListBean.idCardType)) {
            tvIdType.setText("护照");
        } else if ("3".equals(travellerListBean.idCardType)) {
            tvIdType.setText("港澳台胞通行证");
        } else if ("4".equals(travellerListBean.idCardType)) {
            tvIdType.setText("军官证");
        } else if ("5".equals(travellerListBean.idCardType)) {
            tvIdType.setText("士兵证");
        }
        etIdNum.setText(travellerListBean.idCardNum);
        tvBirthday.setText(travellerListBean.birthday);
        sex = travellerListBean.sex;
        if ("1".equals(travellerListBean.sex)) {
            tvSex.setText("男");
        } else if ("0".equals(travellerListBean.sex)) {
            tvSex.setText("女");
        }
        etCountry.setText(travellerListBean.country);
        etPhoneNum.setText(travellerListBean.mobile);
        isMyself = travellerListBean.isMyself;
        if ("1".equals(travellerListBean.isMyself)) {
            toggleButton.setChecked(true);
        } else if ("0".equals(travellerListBean.isMyself)) {
            toggleButton.setChecked(false);
        }

    }

    private ArrayList<String> idCardList = new ArrayList<>();
    private ArrayList<String> sexList = new ArrayList<>();

    @Override
    protected void initView() {
        idCardList.add("身份证");
        idCardList.add("护照");
        idCardList.add("港澳台胞通行证");
        idCardList.add("军官证");
        idCardList.add("士兵证");

        sexList.add("女");
        sexList.add("男");
    }


    private int clickStyle = -1;
    private int IDCARDTYPE = 0x00000001;
    private int SEXTYPE = 0x00000002;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void delPassanger() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("uuids", uuid);

        Call<HttpResult<String>> call = service.delPassanger(JsonUtils.convertParam("delPassanger", h1));
        call.enqueue(new CallbackImpl<String>() {
            @Override
            public void responseSuccess(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                mContext.onBackPressed();
            }
        });

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


    }

    @OnClick({R.id.tv_id_type, R.id.tv_birthday,R.id.tv_sex, R.id.tv_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_id_type:
                clickStyle = IDCARDTYPE;
                showChooseDateDialog(idCardList, "选择证件类型");
                break;
            case R.id.tv_sex:
                clickStyle = SEXTYPE;
                showChooseDateDialog(sexList, "选择性别");
                break;

            case R.id.tv_birthday:
                showDateDialog();
                break;
            case R.id.tv_del:
                delPassanger();
                break;
        }
    }

    private void showDateDialog() {
        Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(mContext, mdateListener, mYear, mMonth, mDay);
        datePickerDialog.show();
    }


    public void display() {
        tvBirthday.setText(new StringBuffer().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay));
    }

    private int mYear;
    private int mMonth;
    private int mDay;
    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display();

        }
    };

    @Override
    protected void getChooseDialog(int index, String message, String title) {
        if (clickStyle == IDCARDTYPE) {
            // 证件类型
            idCardType = index + 1 + "";
            tvIdType.setText(idCardList.get(index));

        } else if (clickStyle == SEXTYPE) {
            sex = index + "";
            tvSex.setText(sexList.get(index));
        }
    }

    private String nameZh;
    private String firstName;
    private String secondName;
    private String idCardType = "1";
    private String idNum;
    private String birthday;
    private String sex = "1";
    private String country;
    private String phoneNum;
    private String isMyself;

    private boolean checkCanUpdate() {
        nameZh = etNameZh.getText().toString().trim();
        firstName = etFirstName.getText().toString().trim();
        secondName = etSecondName.getText().toString().trim();
        idNum = etIdNum.getText().toString().trim();
        birthday = tvBirthday.getText().toString().trim();
        country = etCountry.getText().toString().trim();
        phoneNum = etPhoneNum.getText().toString().trim();

        if (TextUtils.isEmpty(nameZh)) {
            ToastUtil.showToast("请输入中文姓名");
            return false;
        }
        if (TextUtils.isEmpty(firstName)) {
            ToastUtil.showToast("请输入英文姓");
            return false;
        }
        if (TextUtils.isEmpty(secondName)) {
            ToastUtil.showToast("请输入英文名");
            return false;
        }
        if (TextUtils.isEmpty(idCardType)) {
            ToastUtil.showToast("选择证件类型");
            return false;
        }
        if (TextUtils.isEmpty(idNum)) {
            ToastUtil.showToast("请输入证件号码");
            return false;
        }
        if (TextUtils.isEmpty(birthday)) {
            ToastUtil.showToast("请输入生日日期");
            return false;
        }
        if (TextUtils.isEmpty(sex)) {
            ToastUtil.showToast("请选择性别");
            return false;
        }
        if (TextUtils.isEmpty(country)) {
            ToastUtil.showToast("请输入国籍");
            return false;
        }
        if (!StringUtil.isMobile(phoneNum)) {
            ToastUtil.showToast("请输入手机号");
            return false;
        }
        if (toggleButton.isChecked()) {
            isMyself = "1";
        } else {
            isMyself = "0";
        }

        return true;
    }
}
